<template>
  <DialogBox :title="'编辑知识库'" v-model="dialogVisible" width="600" :before-close="closeConfirm">
    <!-- 基本信息  -->
    <BaseForm ref="BaseFormRef" />
    <el-form ref="DatasetFormRef" :rules="rules" :model="datasetForm" label-position="top"
      require-asterisk-position="right">
      <!-- 所属分类 -->
      <el-form-item label="所属分类" prop="perType">
        <el-select v-model="datasetForm.perType" placeholder="请选择所属分类">
          <el-option v-for="item in categorizeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="知识库类型" required>
        <el-radio-group v-model="datasetForm.type" class="card__radio" @change="radioChange">
          <el-row :gutter="20">
            <el-col :span="12" v-if="`${datasetForm.type}` === '0'">
              <el-card shadow="never" class="mb-16" :class="`${datasetForm.type}` === '0' ? 'active' : ''"
                @click="datasetForm.type = 0">
                <div class="flex-between">
                  <div class="flex align-center">
                    <img src="@/assets/dataset/icon_document.svg" style="height:36px" alt="" />
                    <div class="pl-10">
                      <p>
                        <el-text>通用型</el-text>
                      </p>
                      <el-text type="info">上传本地文档</el-text>
                    </div>
                  </div>
                  <el-radio :value="0" size="large" style="width: 16px"></el-radio>
                </div>
              </el-card>
            </el-col>
            <el-col :span="12" v-else>
              <el-card shadow="never" class="mb-16" :class="`${datasetForm.type}` === '1' ? 'active' : ''"
                @click="datasetForm.type = 1">
                <div class="flex-between">
                  <div class="flex align-center">
                    <img src="@/assets/dataset/icon_web.svg" style="height:36px" alt="" />
                    <div class="pl-10">
                      <p>
                        <el-text>web 站点</el-text>
                      </p>
                      <el-text type="info">同步Web网站文本数据</el-text>
                    </div>
                  </div>
                  <el-radio :value="1" size="large" style="width: 16px"></el-radio>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="Web 根地址" prop="sourceUrl" v-if="`${datasetForm.type}` === '1'">
        <el-input v-model="datasetForm.sourceUrl" placeholder="请输入 Web 根地址"
          @blur="datasetForm.sourceUrl = datasetForm.sourceUrl.trim()" />
      </el-form-item>
      <el-form-item label="选择器" v-if="`${datasetForm.type}` === '1'">
        <el-input v-model="datasetForm.selector" placeholder="默认为 body，可输入 .classname/#idname/tagname"
          @blur="datasetForm.selector = datasetForm.selector.trim()" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer res_el-dialog__footer">
        <el-button @click.prevent="closeConfirm" :loading="loading">
          取消
        </el-button>
        <el-button type="primary" @click="submitHandle" :loading="loading">
          保存
        </el-button>
      </span>
    </template>
  </DialogBox>
</template>
<script setup lang="ts">
import { cloneDeep, isEqual, isFunction } from 'lodash'
import { ref, watch, reactive, nextTick } from 'vue'
import BaseForm from './BaseForm.vue'
import { MsgConfirm, MsgError, MsgSuccess } from '@/utils/message'
import { update1 } from '@/servers/ai/api/zhishiku'

import useStore from '@/stores'
const { dataset } = useStore()

const categorizeOptions = ref<any[]>([])

const emit = defineEmits(['refresh'])

const BaseFormRef = ref()
const DatasetFormRef = ref()
const item = ref()

const loading = ref(false)
const dialogVisible = ref<boolean>(false)

const datasetForm = ref<any>({
  type: '0',
  sourceUrl: '',
  selector: '',
  perType: '',
})

const rules = reactive({
  sourceUrl: [
    {
      required: true,
      message: '请输入 Web 根地址',
      trigger: 'blur'
    }
  ],
  perType: [
    {
      required: true,
      message: '请选择分类',
      trigger: 'change'
    }
  ]
})

watch(dialogVisible, (bool) => {
  if (!bool) {
    datasetForm.value = {
      sourceUrl: '',
      selector: '',
      perType: '',
      type: '0',
    }
    DatasetFormRef.value?.clearValidate()
    dialogVisible.value = false

    item.value = {}
  }
})

const open = async (row: any) => {
  // 校验 row 参数
  if (!row) {
    console.error('row 参数不能为空');
    return;
  }

  item.value = row

  // 打开对话框
  dialogVisible.value = true;

  // 获取分类
  const options: any = await dataset.getCategorizeOptions()
  categorizeOptions.value = [...options]

  // 初始化 datasetForm
  initDatasetForm(row);

  // 初始化 BaseFormRef 的数据
  await initBaseFormData(row);
  initFormData.value = cloneDeep({
    ...BaseFormRef.value.form,
    ...datasetForm.value
  })

}

/**
 * 初始化 datasetForm 数据
 */
const initDatasetForm = (row: any) => {
  const { type, perType, selector, sourceUrl } = row
  datasetForm.value = {
    type, // 知识库类型
    perType, // 所属分类
    sourceUrl,
    selector,
  };
};

/**
 * 初始化 BaseFormRef 的数据
 */
const initBaseFormData = async (row: any) => {
  await nextTick(); // 等待 DOM 更新

  if (BaseFormRef.value?.form) {
    BaseFormRef.value.form = {
      name: row.name,
      desc: row.description,
    };
  }
};

const submitHandle = async () => {
  if (await BaseFormRef.value?.validate()) {
    await DatasetFormRef.value.validate((valid: any) => {
      if (valid) {
        loading.value = true
        const baseParams = {
          id: item.value.id,
          maxId: item.value.maxId,
          modeId: item.value.modeId,
        }
        let obj: any = {
          ...baseParams,
          ...BaseFormRef.value.form,
          ...datasetForm.value
        }
        obj.description = obj.desc
        delete obj.desc
        if (`${datasetForm.value.type}` === '0') {
          delete obj.selector
          delete obj.sourceUrl
        }
        update1(obj).then((res: any) => {
          if (res.data.isSuccess) {
            MsgSuccess('保存成功')
            emit('refresh')
            dialogVisible.value = false
          }
        }).catch((e) => {
          MsgError(e.response.data.msg)
        }).finally(() => {
          loading.value = false
        })
      } else {
        return false
      }
    })
  } else {
    return false
  }
}
function radioChange() {
  datasetForm.value.sourceUrl = ''
  datasetForm.value.selector = ''
}

const initFormData: any = ref({})

function closeConfirm (done: () => void) {
  if (isEqual({...datasetForm.value, ...BaseFormRef.value.form }, initFormData.value)) {
    return close(done)
  }
  MsgConfirm('提示', '修改后的信息未保存，确定不保存并关闭弹窗？').then(() => {
    close(done)
  })
}

function close (done: () => void) {
  isFunction(done) && done()
  dialogVisible.value = false
}

defineExpose({ open })
</script>
<style lang="scss" scope></style>
